class GettaPool:
    def __init__(self):
        self._pool = {}
        self._priority_key = []
        self._not_empty_event = asyncio.Event()
        self._not_empty_event.clear()
        self._last_pop_time = time.time()
        self._last_pop_index = -1

    async def pop_wait(self):
        rlt_ = None
        while True:
            for ix_,key_ in enumerate(self._priority_key):
                if self._pool[key_]:
                    if ix_ > 0 and self._last_pop_index > 0 and time.time() - self._last_pop_time < 1:
                        await asyncio.sleep(1)
                        break
                    rlt_ = self._pool[key_][0]
                    del self._pool[key_][0]
                    self._last_pop_index = ix_
                    self._last_pop_time = time.time()
                    break
            if not rlt_:
                await self._not_empty_event.wait()
            else:
                break
        return rlt_

    def pop_nowait(self):
        rlt_ = None
        for ix_,key_ in enumerate(self._priority_key):
            if self._pool[key_]:
                rlt_ = self._pool[key_][0]
                del self._pool[key_][0]
                break
        return rlt_

    def push_nowait(self,priority,task):
        if priority not in self._pool:
            self._priority_key = sorted(self._priority_key + [priority])
            self._pool[priority] = []
        self._pool[priority].append(task)
        self._not_empty_event.set()
